package com.example.homework9;

import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class Fragment2_2 extends Fragment {
    String FILE_NAME="123";
    public Fragment2_2(){
        super(R.layout.fragment2_2);    //外部存储
    }

    private Button writeInternalButton;
    public void onViewCreated(View view, Bundle savedInstanceState){
        super.onViewCreated(view,savedInstanceState);

        writeInternalButton = (Button) getView().findViewById(R.id.writeExternalButton);
        writeInternalButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                File externalPath = getActivity().getExternalFilesDir(null);
                File file = new File(externalPath,FILE_NAME);
                try{
                    FileOutputStream os = new FileOutputStream(file);
                    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os));
                    writer.write("Meiko");
                    writer.close();
                    Toast.makeText(getActivity(),"写入成功",Toast.LENGTH_SHORT).show();
                }catch(Exception e){
                    e.printStackTrace();
                }
            }
        });

        Button readInternalButton = getView().findViewById(R.id.readExternalButton);
        readInternalButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                File externalPath = getActivity().getExternalFilesDir(null);
                File file = new File(externalPath,FILE_NAME);
                try{
                    FileInputStream is = new FileInputStream(file);
                    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                    String line = reader.readLine();
                    Toast.makeText(getActivity(),line,Toast.LENGTH_SHORT).show();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        });
    }
}